package com.tz.crm.controller.customer;

import com.tz.crm.entity.Area;
import com.tz.crm.entity.Contact;
import com.tz.crm.entity.Customer;
import com.tz.crm.service.AreaService;
import com.tz.crm.service.ContactService;
import com.tz.crm.service.CustomerService;
import com.tz.crm.utils.Pager;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2017/3/13 0013.
 */
@Controller
@RequestMapping("/customer")
public class ContactController {
    @Resource
    ContactService contactService;
    @Resource
    CustomerService customerService;
    @Resource
    AreaService areaService;

    /**
     * 访问客户冲突页面
     */
    @RequestMapping("/initConflict")
    public String initConflict(){
        return "customer/customerConflict";
    }

    /**
     * 客户冲突列表查询
     * @return
     */
    @RequestMapping("/conflict")
    public String getList(Pager pager, Contact contact,String provinceId,String cityId, Model model){
        String provinceName;
        String cityName;
        Customer customer = contact.getCustomer();
        if(customer == null){
            customer = new Customer();
        }
        if(areaService.getById(provinceId) != null){
            provinceName = areaService.getById(provinceId).getName();
            customer.setProvinceName(provinceName);
        }
        if(areaService.getById(cityId) != null){
            cityName = areaService.getById(cityId).getName();
            customer.setCityName(cityName);
        }
        contact.setCustomer(customer);

        Pager<Contact> p = contactService.getByPager(pager,contact);
        model.addAttribute("pager",p);
        model.addAttribute("contact",contact);
        return "customer/customerConflict";
    }

    /**
     * 地区级联ajax
     */
    @RequestMapping(value = "/ajaxCityFromProv",method = RequestMethod.POST,produces = "application/json")
    @ResponseBody
    public List<Area> ajaxCityFromProv(String provId){
        List<Area> areas = areaService.getChildrenByParentId(provId);
        List<Area> result = new ArrayList<>();
        for(int i = 0; i < areas.size(); i++){
            Area a = new Area();
            a.setId(areas.get(i).getId());
            a.setName(areas.get(i).getName());
            result.add(a);
        }
        return result;
    }
}
